package com.gitee.neuray.security.modules.param.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.gitee.neuray.security.common.exception.RRException;
import com.gitee.neuray.security.common.utils.PageUtils;
import com.gitee.neuray.security.common.utils.R;
import com.gitee.neuray.security.modules.param.entity.EngineItemEntity;
import com.gitee.neuray.security.modules.param.entity.ParamItemEntity;
import com.gitee.neuray.security.modules.param.service.EngineManageService;
import com.gitee.neuray.security.modules.param.service.EngineParamService;
import com.gitee.neuray.security.modules.param.service.ParamItemService;
import com.gitee.neuray.security.modules.param.util.ExcelUtil;
import com.gitee.neuray.security.modules.sys.entity.SysUserEntity;
import com.gitee.neuray.security.modules.sys.shiro.ShiroUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.*;


/**
 * 发动机表
 *
 * @author neuray
 * @email neuray@neuray.com
 * @date 2020-09-17 09:59:45
 */
@RestController
@RequestMapping("engine/param")
public class EngineParamController {
    @Autowired
    private EngineParamService paramService;
    @Autowired
    private ParamItemService paramItemService;

    /**
     * 列表
     */
    @RequestMapping("/list")
    @RequiresPermissions("engine:param:list")
    public R list(@RequestParam Map params){
        PageUtils ret = paramService.queryTable(params);

        return R.ok().put("page", ret);
    }
    /**
     * 列表
     */
    @RequestMapping("/listColumn")
    @RequiresPermissions("engine:param:listColumn")
    public R listColumn(@RequestParam Map params){
        List<Map> ret = paramService.getColumn(params.get("tableName").toString());

        return R.ok().put("ret", ret);
    }
    @RequestMapping("/getParam")
    @RequiresPermissions("engine:param:getParam")
    public R getParam(@RequestParam Map map){
        String engineId = map.get("id").toString();
        //String engineId = "9PAPsQM0";
        Long deptId = ShiroUtils.getUserEntity().getDeptId();
        List<ParamItemEntity> ret = paramItemService.getParamByEngine(engineId,deptId);
        return R.ok().put("paramList", ret);
    }
    /**
     * 保存
     */
    @RequestMapping("/save")
    @RequiresPermissions("engine:param:save")
    public R save(@RequestBody Map map){

        paramService.saveParam(map);

        return R.ok();
    }
    /**
     * 保存
     */
    @RequestMapping("/update")
    @RequiresPermissions("engine:param:update")
    public R update(@RequestBody Map map){

        paramService.updateParam(map);

        return R.ok();
    }
    /**
     * 保存
     */
    @RequestMapping("/delete")
    @RequiresPermissions("engine:param:delete")
    public R delete(@RequestBody Map map){

        paramService.deleteParam(map);

        return R.ok();
    }
    /**
     * 信息
     */
    /*@RequestMapping("/info/{id}")
    @RequiresPermissions("engine:param:info")
    public R info(@PathVariable("id") String id){
        EngineItemEntity engineItem = engineManageService.getById(id);
        List<ParamItemEntity> params = paramItemService.getParamByEngine(id,ShiroUtils.getUserEntity().getDeptId());
        List<Long> ids = new ArrayList<>();
        params.stream().forEach((param) -> {
            ids.add(param.getId());
        });
        engineItem.setParamIdList(ids);
        return R.ok().put("engineItem", engineItem);
    }

    *//*

    *//**
     * 修改
     *//*
    @RequestMapping("/update")
    @RequiresPermissions("engine:param:update")
    public R update(@RequestBody EngineItemEntity engineItem){
        //ValidatorUtils.validateEntity(engineItem);
        engineManageService.updateEngine(engineItem);
        
        return R.ok();
    }

    *//**
     * 删除
     *//*
    @RequestMapping("/delete")
    @RequiresPermissions("engine:param:delete")
    public R delete(@RequestBody Map map){
        //id
        List<String> ids = (List<String>) map.get("ids");
        //表名
        List<String> list = (List<String>) map.get("obj");;
        engineManageService.deleteEngine(ids,list);

        return R.ok();
    }

    *//**
     * 删除
     *//*
    @RequestMapping("/getParam")
    @RequiresPermissions("engine:param:list")
    public R getParam(){

        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("dept_id",ShiroUtils.getUserEntity().getDeptId());
        List<ParamItemEntity> ret = paramItemService.list(queryWrapper);
        return R.ok().put("paramList", ret);
    }*/

    /**
     *  下载模板
     */
    @RequestMapping("/download/{id}")
    @RequiresPermissions("engine:param:download")
    public void download(HttpServletResponse response,@PathVariable("id") String id) throws Exception{
        String fname = "发动机参数模板.xlsx";// Excel文件名
        OutputStream out = response.getOutputStream();// 取得输出流
        response.reset();// 清空输出流
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fname, "UTF-8")); // 设定输出文件头,该方法有两个参数，分别表示应答头的名字和值。XSSF:xlsx    HSSF:xls  中文要用encode处理一下
        response.setContentType("application/msexcel");
        response.setContentType("text/html; charset=UTF-8"); //设置编码字符
        String [] arr = paramService.getExcelTitleById(id).get("fieldsName").toString().split(",");
        Map param = new HashMap();
        param.put("fieldsName", Arrays.asList(arr));
        try {
            ExcelUtil.process(out,param);

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     *  导出
     */
    @RequestMapping("/export/{id}")
    @RequiresPermissions("engine:param:export")
    public void export(HttpServletResponse response,@PathVariable("id") String id) throws Exception{
        String fname = "发动机参数列表.xlsx";// Excel文件名
        OutputStream out = response.getOutputStream();// 取得输出流
        response.reset();// 清空输出流
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fname, "UTF-8")); // 设定输出文件头,该方法有两个参数，分别表示应答头的名字和值。XSSF:xlsx    HSSF:xls  中文要用encode处理一下
        response.setContentType("application/msexcel");
        response.setContentType("text/html; charset=UTF-8"); //设置编码字符
        Map map = paramService.getExcelTitleById(id);
        String [] arr = map.get("fieldsName").toString().split(",");
        String [] arr1 = map.get("fields").toString().split(",");
        Map param = new HashMap();
        param.put("fieldsName", Arrays.asList(arr));
        param.put("fields", Arrays.asList(arr1));
        // 获取表名
        String tableName = paramService.getTableNameById(id).getTableName();
        param.put("data",paramService.getParamByTable(tableName));
        try {
            ExcelUtil.process(out,param);

        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    /**
     * 上传文件
     */
    @RequestMapping("/importExcel")
    @RequiresPermissions("engine:param:importExcel")
    public R importExcel(@RequestParam("file") MultipartFile file,@RequestParam Map map) throws Exception {
        if (file.isEmpty()) {
            throw new RRException("上传文件不能为空");
        }
        Map title = paramService.getExcelTitleById(map.get("id").toString());
        // 获取表名
        String tableName = paramService.getTableNameById(map.get("id").toString()).getTableName();
        String [] arr = title.get("fieldsName").toString().split(",");
        String [] arr1 = title.get("fields").toString().split(",");
        List<String> titleList = new ArrayList<>();
        SysUserEntity userEntity = ShiroUtils.getUserEntity();
        try {
            XSSFWorkbook workbook = new XSSFWorkbook ( file.getInputStream () );
            //获取第一个sheet页码
            XSSFSheet sheet = workbook.getSheetAt ( 0 );
            // 校验表头
            Map result = checkTitle(arr,sheet.getRow(0));
            if("500".equals(result.get("code"))){
                return R.error(result.get("msg").toString());
            }
            List<String> dataList = new ArrayList<> ( );
            for (int rowNum = 1; rowNum <= sheet.getLastRowNum (); rowNum++) {
                XSSFRow row = sheet.getRow ( rowNum );
                if ( row == null ) {
                    continue;
                }
                String[] str = new String[row.getLastCellNum ()];
                for (int cellNum=0;cellNum<row.getLastCellNum ();cellNum++){
                    Cell cell = row.getCell ( cellNum );
                    if ( cell == null ) {
                        continue;
                    }
                    Object value = getValue ( cell );
                    str[cellNum]="'"+value+"'";
                }
                StringBuffer d = new StringBuffer("(null,");
                // 创建时间
                d.append("current_timestamp,");
                // 创建人id
                d.append(userEntity.getUserId()+",");
                // 创建人姓名
                d.append("'"+userEntity.getUsername()+"',");
                // 修改时间
                d.append("current_timestamp,");
                // 修改人id
                d.append(userEntity.getUserId()+",");
                // 修改人姓名
                d.append("'"+userEntity.getUsername()+"',");
                // 部门id
                d.append(userEntity.getDeptId()+",");
                dataList.add(d.toString()+ StringUtils.join(str,",")+")");
            }
            paramService.saveList(dataList,tableName);
            return R.ok();
        } catch (IOException e) {
            e.printStackTrace ();
            return R.error();
        }
    }

    private Object getValue ( Cell cell ) {
        Object value = null;
        switch (cell.getCellType ()) {
            case STRING:
                value = cell.getRichStringCellValue ().getString ();
                break;
            case NUMERIC:
                if ( DateUtil.isCellDateFormatted ( cell ) ) {
                    value = cell.getDateCellValue ();
                } else {
                    value = cell.getNumericCellValue ();
                }
                break;
            case BOOLEAN:
                value = cell.getBooleanCellValue ();
                break;
            case FORMULA:
                value = cell.getCellFormula ();
                break;
            case _NONE:
                value = null;
                break;
            default:
                break;
        }
        return value;
    }

    private Map checkTitle(String[] arr,XSSFRow row){
        Map result = new HashMap();
        if(row == null || arr.length != row.getLastCellNum()){
            result.put("code","500");
            result.put("msg","表头数量不正确，请重新选择文件或下载模板");
            return result;
        }
        for(int i=0;i<row.getLastCellNum();i++){
            if(!arr[i].equals(row.getCell(i).getStringCellValue())){
                result.put("code","500");
                result.put("msg","表头不正确，请重新选择文件或下载模板");
                return result;
            }
        }
        result.put("code","200");
        return result;
    }
}
